<template>
  <div>
    <my-form-drawer
      :title="title"
      :width="400"
      :visible="visible"
      @ok="auth"
      @cancel="onClose"
    >
      <a-form-model ref="form" :model="form">
        <a-form-model-item label="用户角色" prop="username">
          <a-checkbox-group v-model="form.role" class="margin-t-20">
            <a-row v-for="item in roleList" :key="item.id">
              <a-col :span="24">
                <a-checkbox :value="item.id" name="role">
                  {{ item.name }}
                </a-checkbox>
              </a-col>
              <br />
              <br />
            </a-row>
          </a-checkbox-group>
        </a-form-model-item>
      </a-form-model>
    </my-form-drawer>
  </div>
</template>

<script>
import { getRoles, saveRoles } from "@/services/user";
import { list } from "@/services/role";
import MyFormDrawer from "@/components/drawer/MyFormDrawer";

export default {
  name: "UserAuth",
  components: { MyFormDrawer },
  data() {
    return {
      title: "",
      form: {
        role: []
      },
      visible: false,
      roleList: [],
      page: {
        currentPage: 1,
        pageSize: 20
      },
      uid: 0
    };
  },
  computed: {},
  created() {
    this.getRoleList();
    this.$bus.$on("userAuthVisible", val => {
      this.visible = val.state;
      this.title = "授权用户";
      this.uid = val.data;
      getRoles({ id: this.uid }).then(res => {
        if (res.data.code == 0) {
          this.form.role = res.data.data;
        }
      });
    });
  },
  destroyed() {
    this.$bus.$off("userAuthVisible");
  },
  methods: {
    onClose() {
      this.visible = false;
      this.$refs["form"].clearValidate();
      this.form.role = [];
    },
    getRoleList() {
      this.loading = true;
      list({
        page: this.page.currentPage,
        pageSize: this.page.pageSize
      }).then(res => {
        this.roleList = res.data.data.list;
        this.loading = false;
      });
    },
    //授权
    auth() {
      console.log(this.form.role);
      saveRoles({
        userId: this.uid,
        roleIds: this.form.role
      }).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.$message.success("授权成功");
          this.$emit('refresh');
          this.onClose();
        }
      });
    }
  }
};
</script>

<style lang="less" scoped></style>
